<template>
  <el-dialog v-model="dialogVisible" title="保养任务列表" width="70%" @close="handleClose">
    <!-- 列表 -->
    <ContentWrap>
      <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange" border>
        <el-table-column label="保养单号" align="center" prop="code" />
        <el-table-column label="图号" align="center" prop="drawingNo" min-width="90" />
        <el-table-column label="模具" align="center" prop="accountName" min-width="90" />
        <el-table-column label="编码" align="center" prop="accountCode" min-width="120" />
        <el-table-column label="保养类型" align="center" prop="upkeepCategory" min-width="90" />
        <el-table-column label="接收人" align="center" prop="assigneerName" />
        <el-table-column label="保养人" align="center">
          <template #default="scope">
            <span v-for="(userId, index) in scope.row.assigneerIds" :key="userId">
              {{userList.find(user => user.id === userId)?.nickname}}<span
                v-if="index < scope.row.assigneerIds.length - 1">, </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MOLD_UPKEEP_TOBE_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="计划保养日期" align="center" prop="nextUpkeepTime" :formatter="dateFormatter" width="180px" />
        <!--     <el-table-column label="实际保养日期" align="center" prop="realUpkeepTime" :formatter="dateFormatter" width="180px" />
      -->
        <el-table-column label="下达时间" align="center" prop="taskCreateTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="接收时间" align="center" prop="taskReceiveTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="作业开始时间" align="center" prop="jobStartTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="任务开始时间" align="center" prop="taskStartTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="任务结束时间" align="center" prop="taskEndTime" :formatter="dateFormatter" width="180px" />

        <el-table-column label="操作" align="center" min-width="150px" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="openDetail(scope.row.id)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </ContentWrap>

    <!-- 表单弹窗：报工界面 -->
    <UpkeepWorkPort ref="workPortRef" @success="getList" />

    <!-- 表单弹窗：详情界面 -->
    <UpkeepTaskDetail ref="detailRef" />
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import { UpkeepTaskApi, UpkeepTask, UpkeepTaskModStautus } from '@/api/mold/upkeeptask'
import UpkeepWorkPort from '@/views/mold/upkeeptask/UpkeepWorkPort.vue'
import UpkeepTaskDetail from '@/views/mold/upkeeptask/UpkeepTaskDetail.vue'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'

/** 模具保养任务 列表 */
defineOptions({ name: 'UpkeepTaskList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false)
const loading = ref(true) // 列表的加载中
const list = ref<UpkeepTask[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const accountId = ref<number>() // 传递进来的模具ID

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  accountId: undefined,
  assigneerId: undefined,
  status: undefined,
  taskCreateTime: [],
})
const queryFormRef = ref() // 搜索的表单
const userList = ref<UserVO[]>([])
const detailRef = ref() // 详情弹窗引用
const workPortRef = ref()

/** 获取保养人列表 */
const getUserList = async () => {
  try {
    userList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    message.error('获取保养人列表失败')
    console.error(error)
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 强制设置accountId查询条件
    queryParams.accountId = accountId.value
    const data = await UpkeepTaskApi.getUpkeepTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

//接收
const handleReceive = (id: number) => {
  const status_a: UpkeepTaskModStautus = {
    id: id,
    status: 3,
    data: "" // 3为"已接收"状态，具体值请根据实际业务调整
  }
  modStatus(status_a)
}

//保养
const handleStartJob = (id: number) => {
  //弹窗提醒：开始作业后，将会记录当前时间为作业开始时间，是否确定？
  message.confirm('确认开始作业吗？').then(() => {
    const status_a: UpkeepTaskModStautus = {
      id: id,
      status: 4,
      data: "" // 4为"已开始作业"状态，具体值请根据实际业务调整
    }
    modStatus(status_a)
  })
}

// 打开报工界面
const handleWorkPort = (id: number) => {
  workPortRef.value.open(id)
}

// 打开详情界面
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 调用状态接口 */
const modStatus = async (status_a: UpkeepTaskModStautus) => {
  try {
    await UpkeepTaskApi.modStatus(status_a)
    message.success('操作成功')
    await getList()
  } catch (error) {
    message.error('操作失败')
    // 可选：console.error(error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UpkeepTaskApi.deleteUpkeepTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: UpkeepTask[]) => {
  checkedIds.value = records.map((item) => item.id);
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 打开对话框并传入模具ID
const open = async (id: number) => {
  accountId.value = id
  queryParams.accountId = id
  dialogVisible.value = true
  await getUserList()
  await getList()
}

/** 初始化 **/
onMounted(() => {
  getUserList()
})

// 暴露方法给父组件
defineExpose({
  open
})
</script>